package com.fingard.dsp.bank.directbank.mhcbc01;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.IBalance;
import com.fingard.dsp.bank.reqrespobj.balance.Req7505HisBalQry;
import com.fingard.dsp.bank.reqrespobj.balance.Req7506BalQry;
import com.fingard.dsp.bank.reqrespobj.balance.RetAts7505HisBalQry;
import com.fingard.dsp.bank.reqrespobj.balance.RetAts7506BalQry;
import com.fingard.dsp.bank.reqrespobj.balance.detail.RetAtsBalDetail;
import com.fingard.text.StringHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import javax.xml.crypto.Data;
import java.text.DecimalFormat;
import java.util.Date;


/**
 * @author Alon on 2019-10-21.
 * @version 1.0
 */
public class MHCBC01Balance extends MHCBC01Base implements IBalance {
    @Override
    public RetAts7506BalQry d_7506_BalQry(Req7506BalQry p_req7506) throws Exception {
        //余额查询返回ATS的对象
        RetAts7506BalQry retAts = new RetAts7506BalQry(p_req7506.reqHeader);
        retAts.writeStart();//写返回ATS的统一头部信息
        try {
            WriteBankLogLn("进入余额查询处理类 ");
            int detailNum = 1;
            while (detailNum <= p_req7506.detailCount) {
                XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
                writeCommonHeader(xmlWriter);
                int actNum = 0;//账户个数
                xmlWriter.writeStartElement("trn-qrybal-rq");

                xmlWriter.writeElementString("seqno", Format.DateTime17SSSFormat.format(new Date()).substring(1));//银行接口报文长度固定为16
                xmlWriter.writeStartElement("qrybal-rq");
                xmlWriter.writeElementString("eid", bankFront.org);//企业代码
                xmlWriter.writeElementString("opno", bankFront.operator);//操作员代码
                xmlWriter.writeStartElement("qryactno-info");
                while (p_req7506.readRecord()) {
                    detailNum++;
                    actNum++;
                    xmlWriter.writeElementString("actno", p_req7506.readedDetail.actNum);
                    if (actNum >= 10) {
                        break;
                    }
                }
                xmlWriter.writeEndElement();//</qryactno-info>
                xmlWriter.writeElementString("actnum", actNum + "");//查询账户个数
                xmlWriter.writeEndElement();//</qrybal-rq>
                xmlWriter.writeEndDocument();


                String[] tmpRetBkStr = sendToBank(xmlWriter.toXmlString());
                RetAts7506BalQry errRetAts = new RetAts7506BalQry(p_req7506.reqHeader);//如果异常则返回该结果给ATS
                errRetAts.writeStart();//写返回ATS的统一头部信息
                errRetAts.writeRespCode("-1");

                if (tmpRetBkStr[0].length() == 0) {
                    StringBuilder tmpSbMsg = new StringBuilder();
                    XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpRetBkStr[1], tmpSbMsg);
                    if (tmpBkReader != null) {
                        String returnCode = tmpBkReader.getFirstText("/edes/msg-xdata/trn-qrybal-rs/qrybal-rs/retcode");
                        String returnActNum = tmpBkReader.getFirstText("/edes/msg-xdata/trn-qrybal-rs/qrybal-rs/actnum");//查询返回的账户个数
                        if (Integer.parseInt(returnActNum) != actNum) {
                            WriteBankLogLn("银行返回结果个数与查询账号个数不等！");
                            errRetAts.writeRespInfo("银行返回结果个数与查询账号个数不等！");
                            return errRetAts;
                        } else {
                            if (returnCode != null && "0000".equals(returnCode)) {
                                while (tmpBkReader.read("/edes/msg-xdata/trn-qrybal-rs/qrybal-rs/qryactno-dtl")) {
                                    String succFlag = tmpBkReader.readedXElement.getSingleText("flag");
                                    RetAtsBalDetail tmpRetDetail = new RetAtsBalDetail();
                                    if ("1".equals(succFlag)) {
                                        double bookBalance = Double.parseDouble(tmpBkReader.readedXElement.getSingleText("book-balance"));//返回余额，无小数点精确到分
                                        double availableBalance = Double.parseDouble(tmpBkReader.readedXElement.getSingleText("available-balance"));//返回余额，无小数点精确到分
                                        tmpRetDetail.respCode = "0";
                                        tmpRetDetail.respInfo = "余额查询成功！";
                                        tmpRetDetail.actNum = tmpBkReader.readedXElement.getSingleText("actno");
                                        DecimalFormat df = new DecimalFormat();
                                        String style = "0.00";
                                        df.applyPattern(style);
                                        tmpRetDetail.currBal = df.format(bookBalance / 100.00);//当前余额（表面余额）
                                        tmpRetDetail.availBal = df.format(availableBalance / 100.00);//可用余额（实际余额）
                                        retAts.writeRetDetail(tmpRetDetail, p_req7506.isBatch);
                                    } else {
                                        tmpRetDetail.respCode = "0";
                                        tmpRetDetail.respInfo = "余额查询失败!";
                                        retAts.writeRetDetail(tmpRetDetail, p_req7506.isBatch);
                                    }
                                }
                            } else {
                                if (!StringHelper.isNullOrEmpty(convertRespToBank(returnCode))) {
                                    errRetAts.writeRespInfo("错误代码：" + returnCode + ";" + convertRespToBank(returnCode));
                                } else {
                                    errRetAts.writeRespInfo("错误代码未映射，错误代码：" + returnCode);
                                }
                                errRetAts.writeEnd();
                                return errRetAts;
                            }
                        }
                    } else {
                        errRetAts.writeRespInfo(tmpSbMsg.toString());
                        errRetAts.writeEnd();
                        return errRetAts;
                    }
                } else {
                    errRetAts.writeRespInfo(tmpRetBkStr[1]);
                    errRetAts.writeEnd();
                    return errRetAts;
                }
            }//while detailNum <= p_req7506.detailCount
        } catch (Exception e) {
            retAts.writeRespCode("-1");
            retAts.writeRespInfo(e.getMessage());
            e.printStackTrace();
            WriteBankLogLn("余额查询异常：" + e);
        }
        retAts.writeEnd();
        return retAts;
    }

    @Override
    public RetAts7505HisBalQry d_7505_BalQry(Req7505HisBalQry p_req7505) throws Exception {
        return null;
    }
}
